import os
import json
from datetime import datetime

class HTMLGenerator:
    def __init__(self, images_dir):
        self.images_dir = images_dir

    def generate(self, image_paths, pdf_name, output_dir):
        # Add sys to imports at the top of the file
        import sys
        
        # Validate inputs
        if not image_paths:
            print("Error: No image paths provided", file=sys.stderr)
            raise ValueError("No image paths provided")
            
        if not pdf_name:
            pdf_name = "converted_document"
            
        if not output_dir:
            raise ValueError("Output directory not specified")
            
        # Ensure output directory exists
        os.makedirs(output_dir, exist_ok=True)
            
        # Generate HTML content with detailed error handling
        try:
            html_content = self._generate_html(image_paths, pdf_name)
            if not html_content:
                print("Error: Generated HTML content is empty", file=sys.stderr)
                raise ValueError("Failed to generate HTML content")
        except Exception as e:
            print(f"Error in _generate_html: {str(e)}", file=sys.stderr)
            raise ValueError(f"Failed to generate HTML content: {str(e)}")
            
        # Create HTML file
        base_name = os.path.splitext(os.path.basename(str(pdf_name)))[0]
        html_path = os.path.join(output_dir, f"{base_name}.html")
        
        try:
            with open(html_path, 'w', encoding='utf-8') as f:
                f.write(html_content)
            
            # Generate image paths mapping
            self._generate_image_paths(image_paths, output_dir)
            
            return html_path
            
        except (IOError, OSError) as e:
            raise RuntimeError(f"Failed to write HTML file: {str(e)}")

    def _generate_html(self, image_paths, pdf_name):
        """Generate the HTML content with the given image paths"""
        import sys
        
        if not image_paths:
            print("Error: No image paths provided for HTML generation", file=sys.stderr)
            return None
            
        image_elements = []
        for i, img_path in enumerate(image_paths, 1):
            if not img_path:
                print(f"Warning: Empty image path at index {i-1}", file=sys.stderr)
                continue
                
            try:
                img_name = os.path.basename(str(img_path))
                rel_path = os.path.join('images', img_name).replace('\\', '/')
                img_tag = f'<img src="{rel_path}" alt="第 {i} 页" class="page-image" data-page="{i}">'
                image_elements.append(f'<div class="page-container" id="page-{i}">{img_tag}</div>')
            except Exception as e:
                print(f"Error processing image {i}: {str(e)}", file=sys.stderr)
                continue
                
        if not image_elements:
            print("Error: No valid image elements were generated", file=sys.stderr)
            return None
    
        # Generate HTML template with the image elements
        try:
            # Ensure all image paths are properly formatted
            image_paths_html = '\n'.join(image_elements)
            
            html_template = f"""<!DOCTYPE html>
<html>
<head>
    <title>{os.path.splitext(pdf_name)[0]}</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {{ 
            font-family: Arial, sans-serif; 
            margin: 0; 
            padding: 20px; 
            display: flex;
            flex-direction: column; 
            align-items: center;
            background-color: #f5f5f5;
        }}
        .main-container {{
            display: flex;
            width: 100%;
            max-width: 1200px;
            gap: 20px;
        }}
        .thumbnail-container {{
            width: 150px;
            overflow-y: auto;
            max-height: 800px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            padding: 10px;
        }}
        .thumbnail {{
            width: 100%;
            margin-bottom: 10px;
            cursor: pointer;
            border: 2px solid transparent;
            transition: border-color 0.2s;
        }}
        .thumbnail:hover, .thumbnail.active {{
            border-color: #4CAF50;
        }}
        .viewer-container {{
            flex: 1;
            background: white;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }}
        .toolbar {{
            padding: 10px;
            background: #f0f0f0;
            border-bottom: 1px solid #ddd;
            display: flex;
            gap: 10px;
        }}
        .toolbar button {{
            padding: 5px 10px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }}
        .toolbar button:hover {{
            background: #45a049;
        }}
        .page-container {{
            padding: 20px;
            text-align: center;
        }}
        .page-image {{
            max-width: 100%;
            height: auto;
            box-shadow: 0 0 5px rgba(0,0,0,0.2);
        }}
        .page-navigation {{
            padding: 10px;
            background: #f0f0f0;
            border-top: 1px solid #ddd;
            text-align: center;
        }}
        .page-navigation button {{
            margin: 0 5px;
        }}
    </style>
</head>
<body>
    <div class="main-container">
        <div class="thumbnail-container" id="thumbnailContainer">
            {' '.join([f'<img src="images/{os.path.basename(str(img))}" class="thumbnail" data-target="page-{i}" alt="Page {i}">' for i, img in enumerate(image_paths, 1) if img])}
        </div>
        <div class="viewer-container">
            <div id="toolbar" class="toolbar">
                <button id="prevPage">上一页</button>
                <span id="pageInfo">第 1 页，共 {len(image_paths)} 页</span>
                <button id="nextPage">下一页</button>
                <div style="flex: 1"></div>
                <button id="zoomIn">放大</button>
                <button id="zoomOut">缩小</button>
                <button id="fitWidth">适合宽度</button>
                <button id="fitPage">整页显示</button>
            </div>
            <div id="content" style="flex: 1; overflow: auto; padding: 20px;">
                {' '.join(image_elements)}
            </div>
            <div class="page-navigation">
                <button id="firstPage">首页</button>
                <button id="prevPageBottom">上一页</button>
                <span>第 <span id="currentPage">1</span> 页，共 {len(image_paths)} 页</span>
                <button id="nextPageBottom">下一页</button>
                <button id="lastPage">末页</button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {{
            const pages = document.querySelectorAll('.page-container');
            const thumbnails = document.querySelectorAll('.thumbnail');
            const currentPageEl = document.getElementById('currentPage');
            const pageInfoEl = document.getElementById('pageInfo');
            const totalPages = {len(image_paths)};
            let currentPage = 1;
            let zoomLevel = 1;
            const zoomStep = 0.2;

            function showPage(pageNum) {{
                if (pageNum < 1 || pageNum > totalPages) return;
                
                pages.forEach((page, index) => {{
                    page.style.display = (index + 1 === pageNum) ? 'block' : 'none';
                }});
                
                thumbnails.forEach((thumb, index) => {{
                    if (index + 1 === pageNum) {{
                        thumb.classList.add('active');
                        thumb.scrollIntoView({{ behavior: 'smooth', block: 'nearest' }});
                    }} else {{
                        thumb.classList.remove('active');
                    }}
                }});
                
                currentPage = pageNum;
                currentPageEl.textContent = pageNum;
                pageInfoEl.textContent = `第 ${{currentPage}} 页，共 ${{totalPages}} 页`;
                
                // Update URL hash
                window.location.hash = 'page-' + pageNum;
            }}

            function updateZoom() {{
                const currentImage = document.querySelector('#page-' + currentPage + ' .page-image');
                if (currentImage) {{
                    currentImage.style.transform = 'scale(' + zoomLevel + ')';
                    currentImage.style.transformOrigin = 'top center';
                }}
            }}

            // Navigation event listeners
            document.getElementById('prevPage').addEventListener('click', () => {{
                if (currentPage === 1) {{
                    alert('已经是第一页了');
                }} else {{
                    showPage(currentPage - 1);
                }}
            }});
            document.getElementById('nextPage').addEventListener('click', () => {{
                if (currentPage === totalPages) {{
                    alert('已经是最后一页了');
                }} else {{
                    showPage(currentPage + 1);
                }}
            }});
            document.getElementById('firstPage').addEventListener('click', () => {{
                if (currentPage === 1) {{
                    alert('已经是第一页了');
                }} else {{
                    showPage(1);
                }}
            }});
            document.getElementById('lastPage').addEventListener('click', () => {{
                if (currentPage === totalPages) {{
                    alert('已经是最后一页了');
                }} else {{
                    showPage(totalPages);
                }}
            }});
            document.getElementById('prevPageBottom').addEventListener('click', () => {{
                if (currentPage === 1) {{
                    alert('已经是第一页了');
                }} else {{
                    showPage(currentPage - 1);
                }}
            }});
            document.getElementById('nextPageBottom').addEventListener('click', () => {{
                if (currentPage === totalPages) {{
                    alert('已经是最后一页了');
                }} else {{
                    showPage(currentPage + 1);
                }}
            }});

            // Zoom controls
            document.getElementById('zoomIn').addEventListener('click', () => {{
                zoomLevel += zoomStep;
                updateZoom();
            }});

            document.getElementById('zoomOut').addEventListener('click', () => {{
                if (zoomLevel > zoomStep) {{
                    zoomLevel -= zoomStep;
                    updateZoom();
                }}
            }});

            document.getElementById('fitWidth').addEventListener('click', () => {{
                const currentImage = document.querySelector(`#page-${{currentPage}} .page-image`);
                if (currentImage) {{
                    const container = document.querySelector('.viewer-container');
                    const containerWidth = container.clientWidth - 40; // Account for padding
                    const imageWidth = currentImage.naturalWidth;
                    zoomLevel = containerWidth / imageWidth;
                    updateZoom();
                }}
            }});

            document.getElementById('fitPage').addEventListener('click', () => {{
                const currentImage = document.querySelector(`#page-${{currentPage}} .page-image`);
                if (currentImage) {{
                    const container = document.querySelector('.viewer-container');
                    const containerWidth = container.clientWidth - 40; // Account for padding
                    const containerHeight = container.clientHeight - 120; // Account for toolbars and padding
                    const imageWidth = currentImage.naturalWidth;
                    const imageHeight = currentImage.naturalHeight;
                    
                    // Calculate zoom level to fit both width and height
                    const widthRatio = containerWidth / imageWidth;
                    const heightRatio = containerHeight / imageHeight;
                    zoomLevel = Math.min(widthRatio, heightRatio);
                    
                    updateZoom();
                    
                    // Scroll to top of the viewer
                    const viewer = document.querySelector('.viewer-container');
                    if (viewer) {{
                        viewer.scrollTop = 0;
                    }}
                }}
            }});

            // Thumbnail click handler
            thumbnails.forEach(thumb => {{
                thumb.addEventListener('click', () => {{
                    const targetPage = parseInt(thumb.getAttribute('data-target').split('-')[1]);
                    showPage(targetPage);
                }});
            }});

            // Keyboard navigation
            document.addEventListener('keydown', (e) => {{
                switch(e.key) {{
                    case 'ArrowLeft':
                        if (currentPage === 1) {{
                            alert('已经是第一页了');
                        }} else {{
                            showPage(currentPage - 1);
                        }}
                        break;
                    case 'ArrowRight':
                        if (currentPage === totalPages) {{
                            alert('已经是最后一页了');
                        }} else {{
                            showPage(currentPage + 1);
                        }}
                        break;
                    case 'Home':
                        if (currentPage === 1) {{
                            alert('已经是第一页了');
                        }} else {{
                            showPage(1);
                        }}
                        break;
                    case 'End':
                        if (currentPage === totalPages) {{
                            alert('已经是最后一页了');
                        }} else {{
                            showPage(totalPages);
                        }}
                        break;
                }}
            }});

            // Handle hash on page load
            if (window.location.hash) {{
                const match = window.location.hash.match(/page-(\d+)/);
                if (match) {{
                    showPage(parseInt(match[1]));
                    return;
                }}
            }}
            
            // Show first page by default
            showPage(1);
        }});
    </script>
</body>
</html>"""
            
            return html_template
                
        except Exception as e:
            import sys
            print(f"Error generating HTML template: {str(e)}", file=sys.stderr)
            return None

    def _generate_image_paths(self, image_paths, output_dir):
        """Generate a JSON file with image paths for reference"""
        if not image_paths or not output_dir:
            return
            
        try:
            image_data = {
                'images': [os.path.basename(str(path)) for path in image_paths if path],
                'count': len(image_paths),
                'generated_at': str(datetime.now())
            }

            json_path = os.path.join(output_dir, 'image_paths.json')
            with open(json_path, 'w', encoding='utf-8') as f:
                json.dump(image_data, f, indent=2, ensure_ascii=False)
                
        except (IOError, OSError, TypeError) as e:
            print(f"Warning: Failed to generate image paths JSON: {str(e)}", file=sys.stderr)